package com.wyh.order.controller;

import com.wyh.order.model.DO.OrderInfo;
import com.wyh.order.model.DO.ProductInfo;
import com.wyh.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("order")
public class OrderInfoController {
    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    //计数器
    private AtomicInteger count = new AtomicInteger(1);

    private List<ServiceInstance> instances;
    //从Eureka获取服务列表
    @PostConstruct
    public void init(){
        instances = discoveryClient.getInstances("product-service");
    }


//    @RequestMapping("/{orderId}")
//    public OrderInfo selectOrderById(@PathVariable("orderId") Integer orderId){
//        OrderInfo orderInfo = orderInfoService.selectOrderById(orderId);
////        String url = "http://127.0.0.1:8082/product/" + orderInfo.getProductId();
////        System.out.println(instances.toString());
//        int index = count.getAndIncrement()%instances.size();
//        String uri = instances.get(index).getUri().toString();
//        String url = uri + "/product/" + orderInfo.getProductId();
//        System.out.println(url);
//        ProductInfo forObject = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(forObject);
//        return orderInfo;
//    }

    @RequestMapping("/{orderId}")
    public OrderInfo selectOrderById(@PathVariable("orderId") Integer orderId){
        OrderInfo orderInfo = orderInfoService.selectOrderById(orderId);
        String url = "http://product-service/product/" + orderInfo.getProductId();
//        System.out.println(instances.toString());
//        int index = count.getAndIncrement()%instances.size();
//        String uri = instances.get(index).getUri().toString();
//        String url = uri + "/product/" + orderInfo.getProductId();
        System.out.println(url);
        ProductInfo forObject = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(forObject);
        return orderInfo;
    }
}
